package cn.pconline.autoclub.service;

import cn.pconline.autoclub.util.ClubModule;
import cn.pconline.autoclub.entity.ClubModuleRelation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.Mid;
import org.gelivable.dao.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;

/**
 *
 * @author ppc
 */
public class ClubModuleService {

    @Autowired
    private GeliDao geliDao;
    @Autowired
    private GeliOrm geliOrm;
    public static final Map<Long, ClubModule> moduleMap = new TreeMap<Long, ClubModule>();
    public static final long MODULE_ID_FOCUS_IMG = 1;
    public static final long MODULE_ID_DYNA = 2;
    public static final long MODULE_ID_ACTIVITY = 3;
    public static final long MODULE_ID_PHOTO = 4;
    public static final long MODULE_ID_DIARY = 5;

    static {
        moduleMap.put(MODULE_ID_FOCUS_IMG, new ClubModule(MODULE_ID_FOCUS_IMG, "http://www1.pcauto.com.cn/2014/club/v4_1/bj_focus.png", "焦点图", ClubModuleRelation.STATUS_NORMAL));
        moduleMap.put(MODULE_ID_DYNA, new ClubModule(MODULE_ID_DYNA, "http://www1.pcauto.com.cn/2014/club/v4_1/bj_dongtai.png", "最新动态", ClubModuleRelation.STATUS_NORMAL));
        moduleMap.put(MODULE_ID_ACTIVITY, new ClubModule(MODULE_ID_ACTIVITY, "http://www1.pcauto.com.cn/2014/club/v4_1/bj_activity.png", "最新活动", ClubModuleRelation.STATUS_NORMAL));
        moduleMap.put(MODULE_ID_PHOTO, new ClubModule(MODULE_ID_PHOTO, "http://www1.pcauto.com.cn/2014/club/v4_1/bj_photo.png", "相册", ClubModuleRelation.STATUS_NORMAL));
        moduleMap.put(MODULE_ID_DIARY, new ClubModule(MODULE_ID_DIARY, "http://www1.pcauto.com.cn/2014/club/v4_1/bj_diary.png", "活动日记", ClubModuleRelation.STATUS_NORMAL));
    }

    /**
     * 根据ID获取车友会版块
     *
     * @param forumId
     * @return
     */
    public ClubModule getClubModule(long moduleId) {
        return moduleMap.get(moduleId);
    }

    /**
     * 获取车友会模块列表
     *
     * @param clubBlockForumRelations
     */
    private void findWithClubModules(List<ClubModuleRelation> clubBlockForumRelations) {
        if (clubBlockForumRelations != null && !clubBlockForumRelations.isEmpty()) {
            for (ClubModuleRelation relation : clubBlockForumRelations) {
                relation.setClubModule(getClubModule(relation.getModuleId()));
            }
        }
    }

    /**
     * 根据车友会ID 状态获取版块列表(排序完)
     *
     * @param clubId
     * @param status
     * @return
     */
    public List<ClubModuleRelation> listClubModuleRelationsByClub(long clubId, int status) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select * from ").appendSql(geliOrm.getTableName(ClubModuleRelation.class)).appendSql(" where club_id=").appendValue(clubId);
        if (status != ClubModuleRelation.STATUS_ALL) {
            sql.appendSql(" and status=").appendValue(status);
        }
        sql.appendSql(" order by seq");
        List<ClubModuleRelation> clubBlockForumRelations = geliDao.list(ClubModuleRelation.class, sql.getSql(), sql.getValues());
        return clubBlockForumRelations;
    }

    /**
     * 查找可见的模块ID
     * @param clubId
     * @return 
     */
    public List<Long> getNormalModuleIdsByClub(long clubId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select module_id,status from ").appendSql(geliOrm.getTableName(ClubModuleRelation.class)).appendSql(" where club_id=").appendValue(clubId);
        sql.appendSql(" order by seq");
        List<Long> ids = new ArrayList<Long>();
        boolean isNeedDefault = true;
        try {
            List<Map<String, Object>> maps = geliDao.getJdbcTemplate().queryForList(sql.getSql(), sql.getValues());
            for (Map<String, Object> m : maps) {
                isNeedDefault = false;
                if (ClubModuleRelation.STATUS_NORMAL == (Integer)m.get("status")) {
                    ids.add((Long)m.get("module_id"));
                }
            }
        } catch (EmptyResultDataAccessException e) {
        }
        if (ids.isEmpty() && isNeedDefault) {
            Object[] ks = moduleMap.keySet().toArray();
            for (Object o : ks) {
                ids.add((Long) o);
            }
        }
        return ids;
    }

    public List<ClubModuleRelation> listAllClubModuleRelationsByClub(long clubId) {
        List<ClubModuleRelation> clubModuleRelations = listClubModuleRelationsByClub(clubId, ClubModuleRelation.STATUS_ALL);
        if (clubModuleRelations != null && !clubModuleRelations.isEmpty()) {
            findWithClubModules(clubModuleRelations);
            return clubModuleRelations;
        }
        Object[] ids = moduleMap.keySet().toArray();
        clubModuleRelations = new ArrayList<ClubModuleRelation>(ids.length);
        for (int i = 0; i < ids.length; i++) {
            ClubModule clubModule = moduleMap.get(ids[i]);
            ClubModuleRelation clubModuleRelation = new ClubModuleRelation();
            clubModuleRelation.setClubId(clubId);
            clubModuleRelation.setModuleId(clubModule.getModuleId());
            clubModuleRelation.setStatus(clubModule.getStatus());
            clubModuleRelation.setSeq(i + 1);
            clubModuleRelation.setClubModule(clubModule);
            clubModuleRelations.add(clubModuleRelation);
        }
        return clubModuleRelations;

    }

    public int addOrUpdateClubModules(List<ClubModuleRelation> clubModuleRelations) {
        if (clubModuleRelations != null && !clubModuleRelations.isEmpty()) {
            SqlBuilder sql = new SqlBuilder();
            sql
                    .appendSql("insert into ").appendSql(geliOrm.getTableName(ClubModuleRelation.class)).appendSql("(club_id,module_id,status,seq)  values(?,?,?,?) ON DUPLICATE KEY UPDATE status = ?,seq = ?");
            List<Object[]> objArgs = new ArrayList<Object[]>();
            for (ClubModuleRelation clubModuleRelation : clubModuleRelations) {
                List<Object> obj = new ArrayList<Object>();
                obj.add(clubModuleRelation.getClubId());
                obj.add(clubModuleRelation.getModuleId());
                obj.add(clubModuleRelation.getStatus());
                obj.add(clubModuleRelation.getSeq());
                obj.add(clubModuleRelation.getStatus());
                obj.add(clubModuleRelation.getSeq());
                objArgs.add(obj.toArray());
            }
            int count = geliDao.getJdbcTemplate().batchUpdate(sql.getSql(), objArgs).length;
            //清除缓存
            clearCache(clubModuleRelations);
            return count;
        }
        return 0;
    }

    /**
     * 批量更新后清除缓存
     *
     * @param clubModuleRelations
     */
    private void clearCache(List<ClubModuleRelation> clubModuleRelations) {
        if (clubModuleRelations != null && !clubModuleRelations.isEmpty()) {
            for (ClubModuleRelation clubModuleRelation : clubModuleRelations) {
                geliDao.deleteCache(ClubModuleRelation.class, new Mid(clubModuleRelation.getClubId(), clubModuleRelation.getModuleId()));
            }
        }
    }
}
